﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;
using System.Linq;
using RssReaderTemplate.Model.Mappers;

namespace RssReaderTemplate.Model
{
    public class RssParser
    {
        protected string _feed;
        protected ItemMapper _mapper;
        public RssParser(string rssFeed)
        {
            _feed = rssFeed;
        }

        public IEnumerable<RssItem> ParseFeed()
        {
            StringReader str = new StringReader(_feed);
            XmlReader reader = XmlReader.Create(str);
            SyndicationFeed feed = SyndicationFeed.Load(reader);
            IEnumerable<SyndicationItem> items = feed.Items;
            ItemMapper mapper = GetMapper(items.First());
            return items.Select(x => mapper.MapItem(x));
        }

        private ItemMapper GetMapper(SyndicationItem syndicationItem)
        {
            if (_mapper == null)
            {
                _mapper = MapperProvider.CreateMapper(syndicationItem); 
            }
            return _mapper; 
        }
    }
}
